const mongoose = require('mongoose')
const {formatDate} = require('../utils/utils')
const {uploadURL, serverURL} = require("../config");
const { filterAndTruncateContent } = require("../utils/utils");
const schema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    default: '默认标题' + new Date().toDateString(),
  },
  //封面图
  cover: {
    type: String, //URL
    default: `/img/article-cover.jpg`,
  },
  //文章内容
  content: {
    type: String,
    set(val) {
      try {
        return decodeURIComponent(val)
      } catch (err) {
        return val
      }
    },
    required: true,
  },
  //点击量
  hit_num: {
    type: Number,
    default: 0,
  },
  // 草稿箱
  is_draft: {
    type: Boolean,
    enum: [true, false],
    default: false,
  },
  //是否是markdown,区分markdown和富文本编辑器
  is_markdown: {
    type: Boolean,
    enum: [true, false],
    default: false,
  },
  //收藏数量
  favorite_num: {
    type: Number,
    default: 0,
  },
  //点赞数量
  like_num: {
    type: Number,
    default: 0,
  },
  //更新日期
  date: {
    type: mongoose.SchemaTypes.Date,
    default: Date.now,
    get(val) {
      return formatDate(new Date(val), 'yyyy年MM月dd日 hh:mm:ss')
    },
  },
  //作者
  author: {
    type: mongoose.SchemaTypes.ObjectId,
    required: true,
    ref: 'User',
  },
  //评论集合
  comments: [
    {
      type: mongoose.SchemaTypes.ObjectId,
      ref: 'Comment',
    },
  ],
  //分类
  category: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: 'Category',
    required: true,
  },
})
// 定义一个虚拟字段，用于获取评论数量
schema.virtual("comment_num").get(function () {
  if (!this.comments) return 0;
  return this.comments.length;
});
// 定义一个虚拟字段，用于获取文章封面图的完整URL
schema.virtual("cover_img").get(function () {
  if (this.cover === "/img/article-cover.jpg") {
    return serverURL + this.cover;
  } else {
    return uploadURL + this.cover;
  }
});
// 定义一个虚拟字段，用于获取文章简介
schema.virtual("intro").get(function () {
  // 确保 content 存在且是字符串
  if (typeof this.content !== "string") {
    return "";
  }
  // 过滤掉HTML标签
  // 如果过滤后的字符长度超过100，则截断
  return filterAndTruncateContent(this.content, 100);
});

schema.set('toJSON', {getters: true, versionKey: false, virtuals: true})

const mongoosePaginate = require('mongoose-paginate-v2')
schema.plugin(mongoosePaginate)
module.exports = mongoose.model('Article', schema)
